'use strict';

new Vue({
    el: '#app',
    memo: {
        areaInfo: {},
    },
    submiting: false,
    data: {
        selectedTab: '0',
        // 申请记录相关
        pageNo: 1,
        total: 0,
        histories: [],
        pageSize: 10,
        // 申请详情相关
        showDetail: false,
        // 申请表单相关
        provinces: [],
        cities: [],
        districts: [],
        streets: [],
        parentSiteData: [],
        applyForm: {
            siteName: '',
            siteType: '独立网点',
            address: '',
            adminName: '',
            idCard: '',
            nextSiteCode: '',
            phone: '',
            mobile: '',
            secondPhone: '',
            parentSite: '',
            zipCode: '',
            selectedCity: '',
            selectedProvince: '',
            selectedDistrict: '',
            selectedStreet: '',
        },
        applyResult: {
            id: '',
            siteName: '',
            siteCode: '',
            account: '',
            password: '',
            auditIdea: '',
            auditStatus: ''
        },
        rules: {
            siteName: {
                required: true,  
                validator: function (_, value, callback) {
                    if (value === '') {
                        return callback('网点名称不能为空');
                    }
                    if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
                        return callback('网点名称只能为汉字');
                    }
                    if (value.length > 10) {
                        return callback('网点名称长度不能大于10');
                    }
                    $.get('/branch/querysitename', { siteName: value })
                        .done(function (res) {
                            if (!res.Status) {
                                return callback('网点名称查询失败');
                            }

                            if (res.Data) {
                                return callback('网点名称已被占用');
                            }
                            callback();
                        });
                },
                trigger: 'blur' 
            },
            siteType: {
                required: true,
                message: '请选择网点类型',
                trigger: 'submit' 
            },
            address: {
                required: true,
                message: '地址不能为空',
                trigger: 'submit' 
            },
            adminName: {
                required: true,
                message: '管理员名称不能为空',
                trigger: 'submit' 
            },
            idCard: {
                required: true,
                validator: function (_, value, callback) {
                    if (!value) {
                        callback(new Error('身份证号不能为空'));
                        return;
                    }
                    
                    var regx = /^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}[\dXx]$/

                    if (!regx.test(value)) {
                        callback(new Error('身份证号格式不正确'))
                       return;
                    }

                    callback();
                },
                trigger: 'submit' 
            },
            nextSiteCode: {
                required: true,
                validator: function (_, value, callback) {
                    if (value === '') {
                        return callback('下一站编号不能为空');
                    }
                    $.post('/branch/getobjectbycodeorname', { code: value })
                        .done(function (res) {
                            if (!res.Status) {
                                return callback('下一站编号查询失败');
                            }

                            if (!res.Data) {
                                return callback('下一站编号不存在');
                            }
                            callback();
                        });
                },
                trigger: 'blur' 
            },
            phone: {
                required: true,
                validator: function (_, value, callback) {
                    if (!value) {
                        callback(new Error('查询电话不能为空'));
                        return;
                    }
                    if (!checkMobileAndPhone(value)) {
                        callback(new Error('查询电话格式不正确'));
                        return;
                    }
                    callback();
                },
                trigger: 'submit' 
            },
            mobile: {
                required: true,
                validator: function (_, value, callback) {
                    if (!value) {
                        callback(new Error('手机号码不能为空'));
                        return;
                    }

                    var regx = /^(?:(?:\+|00)86)?1\d{10}$/;

                    if (!regx.test(value)) {
                        callback(new Error('手机号码格式不正确'));
                        return;
                    }

                    callback();

                },
                trigger: 'submit'
            },
            secondPhone: {
                required: true,
                validator: function (_, value, callback) {
                    if (!value) {
                        callback(new Error('异常查件电话不能为空'));
                        return;
                    }
                    if (!checkMobileAndPhone(value)) {
                        callback(new Error('异常查件电话格式不正确'));
                        return;
                    }
                    callback();
                },
                trigger: 'submit' 
            },
            parentSite: {
                required: true,
                message: '所属网点不能为空',
                trigger: 'submit' 
            },
            selectedProvince: {
                required: true,
                message: '省份不能为空',
                trigger: 'submit' 
            },
            selectedCity: {
                required: true,
                message: '城市不能为空',
                trigger: 'submit' 
            },
            selectedDistrict: {
                required: true,
                message: '区/县不能为空',
                trigger: 'submit' 
            },
        }
    },
    computed: {
        // 独立网点初始状态为2
        // 承包区初始状态为0
        submitStatus: function () {
            return this.auditingStatus;
        },
        auditingStatus: function () {
            var status = this.applyResult.auditStatus;
            var type = this.applyForm.siteType;
            if (type === '承包区' && status == 0) {
                return true;
            }
            if (type !== '承包区' && status == 2) {
                return true;
            }
            return false;
        },
        auditOkStatus: function () {
            var status = this.applyResult.auditStatus;
            if (status == 5) {
                return true;
            }
            return false;
        },
        auditFailStatus: function () {
            var status = this.applyResult.auditStatus;
            if (status == 1 || status == 3) {
                return true;
            }
            return false;
        },
        // 申请记录相关
        total: function () {
            return this.histories.length;
        },
        // 申请表单相关
        parentSiteLabel: function () {
            return this.applyForm.siteType === '承包区' ? '所属网点:' : '所属省区:';
        },
        provinces: function () {
            var self = this;
            return this.cityData.map(function (item, idx) {
                self.$options.memo.provinceIndexMap[item.value] = idx;
                return {
                    label: item.label,
                    value: item.value
                };
            });
        },
        cities: function () {
            var selectedProvince = this.applyForm.selectedProvince;
            
            if (!selectedProvince) {
                return [];
            }

            var provinceIndexMap = this.$options.memo.provinceIndexMap;
            var pIdx = provinceIndexMap[selectedProvince];
            
            var currentCities = this.cityData[pIdx].children;
            this.$options.memo.currentCities = currentCities;

            var self = this;
            return currentCities.map(function (item, idx) {
                self.$options.memo.cityIndexMap[item.value] = idx;
                return {
                    label: item.label,
                    value: item.value
                };
            });
        }, 
        districts: function () {
            var selectedCity = this.applyForm.selectedCity;
            
            if (!selectedCity) {
                return [];
            }

            var cityIndexMap = this.$options.memo.cityIndexMap;
            var cIdx = cityIndexMap[selectedCity];
            var currentCities = this.$options.memo.currentCities;
            
            return currentCities[cIdx].children;
        },
    },
    created: function () {
        this.fetchAreaInfo(0, '86');
    },
    methods: {
        selectTab: function (tabIdx) {
            this.selectedTab = tabIdx;
            this.showDetail = false;
            this.onResetForm();
            if (this.selectedTab == 1) {
                this.fetchHistory();
            }
        },
        fetchAreaInfo: function (type, value) {
            var self = this;

            switch (type) {
                case 0:
                    var showErrorMsg = function (callback) {
                        callback('查询省份数据失败');
                    };
                    var setData = function (data) {
                        self.provinces = data;
                    };
                    break;
                case 1:
                    var showErrorMsg = function (callback) {
                        callback('查询城市数据失败');
                    };
                    var setData = function (data) {
                        self.cities = data;
                        self.districts = [];
                        self.streets = [];
                    };
                    break;
                case 2:
                    var showErrorMsg = function (callback) {
                        callback('查询区县数据失败');
                    };
                    var setData = function (data) {
                        self.districts = data;
                        self.streets = [];
                    };
                    break;
                case 3:
                    var showErrorMsg = function (callback) {
                        callback('查询街道数据失败');
                    };
                    var setData = function (data) {
                        self.streets = data;
                    };
                    break;
            }

            if (this.$options.memo.areaInfo[value]) {
                setData(this.$options.memo.areaInfo[value]);
            } else {
                $.get('/branch/getareabyparentid', { parentId: value })
                    .done(function (res) {
                        console.log(res);
                        if (!res.Status) {
                            showErrorMsg(this.$message.error);
                            return;
                        }

                        if (res.Data && Array.isArray(res.Data.rows)) {
                            var arr = res.Data.rows.map(function (item) {
                                return {
                                    value: item.id,
                                    label: item.fullName
                                };
                            });
                            setData(arr);
                            self.$options.memo.areaInfo[value] = arr;
                        }
                    });
            }
        },
        setArea: function (type, data) {
            switch (type) {
                case 1:
                    this.applyForm.selectedProvince = data;
                    this.applyForm.selectedCity = '';
                    this.applyForm.selectedDistrict = '';
                    this.applyForm.selectedStreet = '';
                    break;
                case 2:
                    this.applyForm.selectedCity = data;
                    this.applyForm.selectedDistrict = '';
                    this.applyForm.selectedStreet = '';
                    break;
                case 3:
                    this.applyForm.selectedDistrict = data;
                    this.applyForm.selectedStreet = '';
                    break;
                case 4:
                    this.applyForm.selectedStreet = data;
                    this.applyForm = shallowCopy(this.applyForm);
                    break;
            }
        },
        onSelectArea: function (type, data) {
            console.log('onSelectArea_data:', data);
            this.setArea(type, data);
            this.fetchAreaInfo(type, data.split('_')[1]);
        },
        onResubmit: function () {
            this.selectedTab = '0';
            this.showDetail = false;
            this.applyResult.id = '';
        },
        onSubmitForm: function (status) {
            var self = this;
            if (self.$options.submiting) {
                return;
            }
            self.$refs['applyForm'].validate(function (valid) {
                if (valid) {
                    var selectedProvince = self.applyForm.selectedProvince.split('_');
                    var selectedCity = self.applyForm.selectedCity.split('_');
                    var selectedDistrict = self.applyForm.selectedDistrict.split('_');
                    var selectedStreet = self.applyForm.selectedStreet.split('_');
                    var parentSite = JSON.parse(self.applyForm.parentSite);
                    var params = {
                        FullName: self.applyForm.siteName,
                        CategoryCode: self.applyForm.siteType,
                        ParentName: parentSite.fullName,
                        ParentId: parentSite.id,
                        ParentCode: parentSite.code,
                        Adminname: self.applyForm.adminName,
                        Adminchinaid: self.applyForm.idCard,
                        Adminmobile: self.applyForm.mobile,
                        OuterPhone: self.applyForm.phone,
                        InnerPhone: self.applyForm.secondPhone,
                        Address: self.applyForm.address,
                        PostalCode: self.applyForm.zipCode,
                        PreOrNexStaId: self.applyForm.nextSiteCode,
                        Country: '中国',
                        CountryId: 86,
                        Province: selectedProvince[0],
                        ProvinceId: selectedProvince[1],
                        City: selectedCity[0],
                        CityId: selectedCity[1],
                        District: selectedDistrict[0],
                        DistrictId: selectedDistrict[1],
                        Street: selectedStreet[0],
                        StreetId: selectedStreet[1],
                        AuditStatus: self.applyForm.siteType === '承包区' ? 0 : 2,
                    };
                    if (self.applyResult.id) {
                        params.Id = self.applyResult.id;
                    }
                    if (status) {
                        params.AuditStatus = status;
                    }
                    self.$options.submiting = true;
                    $.post('/branch/savedotapprovaldata', params).done(function (res) {
                        console.log(res);
                        self.$options.submiting = false;

                        if (!res.Status) {
                            self.$message.error(res.StatusMessage);
                            return;
                        }

                        // 撤销申请
                        if (status == 4) {
                            return;
                        }

                        // 提交以及修改表单
                        if (res.ResultValue) {
                            self.$message.success('提交成功');
                            self.selectedTab = '1';
                            self.parentSiteData = [];
                            self.onRowClick({ ID: res.ResultValue });
                        }
                    }).fail(function () {
                        self.$options.submiting = false;
                    });
                    return true;
                } else {
                    return false;
                }
            });
        },
        onChangeSiteType: function () {
            this.applyForm.parentSite = '';
            this.parentSiteData = [];
        },
        onResetForm: function () {
            this.applyForm = {
                siteName: '',
                siteType: '独立网点',
                address: '',
                adminName: '',
                idCard: '',
                nextSiteCode: '',
                phone: '',
                mobile: '',
                secondPhone: '',
                parentSite: '',
                zipCode: '',
                selectedCity: '',
                selectedProvince: '',
                selectedDistrict: '',
                selectedStreet: '',
            };
            this.parentSiteData = [];
            this.applyResult = {
                id: '',
                siteName: '',
                siteCode: '',
                account: '',
                password: '',
                auditIdea: '',
                auditStatus: ''
            };
        },
        onQueryParentSite: debounce(function (value) {
            console.log(value);

            if (!value) {
                return;
            }

            var self = this;

            $.get('/branch/fuzzysearchbycategoryandkey', { key: value, category: this.applyForm.siteType })
                .done(function (res) {
                    console.log(res);

                    if (!res.Status) {
                        return;
                    }
                    if (res.Data && res.Data.rows) {
                        var rows = res.Data.rows.map(function (row) {
                            return {
                                label: row.fullName,
                                value: {
                                    fullName: row.fullName,
                                    id: row.id,
                                    code: row.code,
                                },
                            };
                        });
                        self.parentSiteData = rows;
                        console.log('remote parentSiteData:', self.parentSiteData);
                    }
                });
        }, 300),
        // 申请历史相关
        onRowClick: function (row) {
            this.showDetail = true;
            this.fetchApplyDetailInfo(row.ID);
        },
        onSizeChange: function (pageSize) {
            console.log(`每页 ${pageSize} 条`);
            this.pageSize = pageSize;
            this.fetchHistory();
        },
        onCurrentChange: function (currentPage) {
            console.log(`当前页: ${currentPage}`);
            this.currentPage = currentPage;
            this.fetchHistory();
        },
        cellClassName: function ({ row, _, __, columnIndex }) {
            if (columnIndex === 0) {
                switch (Number(row.AUDIT_STATUS)) {
                    case 1:
                    case 3:
                        return 'approval-result-return';
                    case 5:
                        return 'approval-result-pass';
                }
            }
            return '';
        },
        onPageNoChange: function (pageNo) {
            this.pageNo = pageNo;
            this.fetchHistory();
        },
        fetchHistory: function () {
            var self = this;
            $.get('/branch/getdotapprovallistbyapplywebapiuseridtopage', {
                pageSize: self.pageSize,
                pageNo: self.pageNo,
            }).done(function (res) {
                console.log('fetchHistory res:', res);
                if (!res.Status) {
                    self.$message.error(res.StatusMessage);
                    return;
                }
                if (res.Data) {
                    if (self.pageNo === 1) {
                        self.total = res.Data.totalRows;
                    }
                    self.histories = JSON.parse(res.Data.rows);
                }
            });
        },
        formatDate: function (_, __, time) {
            return time && time.split(' ')[0].split('T')[0];
        },
        formatAuditStatus: function (_, __, status) {
            status = Number(status);
            switch (status) {
                case 0:
                case 2:
                    return '审核中';
                case 1:
                case 3:
                    return '已驳回';
                case 4:
                    return '已撤回';
                case 5:
                    return '审核通过';
                default:
                    return '';
            }
        },
        // 申请详情相关
        fetchApplyDetailInfo: function (id) {
            var self = this;
            $.get('/branch/getdotapprovaldatabyid', { id: id })
                .done(function (res) {
                    console.log('fetchApplyDetailInfo_res:', res);
                    if (!res.Status) {
                        self.$message.error(res.StatusMessage);
                        return;
                    }
                    if (res.ResultValue) {
                        var detail = JSON.parse(res.ResultValue)[0];
                        console.log('detail:', detail);
                        self.parentSiteData = [{
                            label: detail.PARENT_NAME,
                            value: {
                                fullName: detail.PARENT_NAME,
                                id: detail.PARENT_ID,
                                code: detail.PARENT_CODE,
                            },
                        }];
                        self.applyForm = {
                            siteName: detail.FULL_NAME,
                            siteType: detail.CATEGORY_CODE,
                            address: detail.ADDRESS,
                            adminName: detail.ADMINNAME,
                            idCard: detail.ADMINCHINAID,
                            nextSiteCode: detail.PREORNEX_STA_ID,
                            phone: detail.OUTER_PHONE,
                            mobile: detail.ADMINMOBILE,
                            secondPhone: detail.INNER_PHONE,
                            parentSite: JSON.stringify(self.parentSiteData[0].value),
                            zipCode: detail.POSTAL_CODE,
                        };
                        self.onSelectArea(1, detail.PROVINCE + '_' + detail.PROVINCE_ID);
                        self.onSelectArea(2, detail.CITY + '_' + detail.CITY_ID);
                        self.onSelectArea(3, detail.DISTRICT + '_' + detail.DISTRICT_ID);
                        if (detail.STREET && detail.STREET_ID) {
                            self.setArea(4, detail.STREET + '_' + detail.STREET_ID);
                        }
                        self.applyResult = {
                            id: detail.ID,
                            siteName: detail.FULL_NAME,
                            siteCode: detail.CODE,
                            account: detail.USER_NAME,
                            password: detail.USER_PASSWORD,
                            auditIdea: detail.AUDIT_IDEA,
                            auditStatus: detail.AUDIT_STATUS,
                        };
                    }
                })
        },
        onCancelApply: function () {
            this.onSubmitForm(4);
            this.selectedTab = '0';
            this.showDetail = false;
        }
    },
});
